package com.szlanyou.thirdsdk.retrofit.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 陈章
 * create at 2021/7/19 17:01
 * desc:
 * 管理页面请求标识，用于生成唯一的请求码。
 */
public class RequestPageFlagManager {
    private Map<String, RequestPageFlagEntity> requestPageFlagEntityMap = new LinkedHashMap<>();

    /**
     * 标识某个页面
     * @param requestPageFlag
     */
    private void mark(String requestPageFlag) {
        RequestPageFlagEntity requestPageFlagEntity = requestPageFlagEntityMap.get(requestPageFlag);
        if (requestPageFlagEntity == null) {
            requestPageFlagEntityMap.put(requestPageFlag, new RequestPageFlagEntity(requestPageFlag));
        }
    }


    /**
     * 自动生成某个页面的请求码
     * @param requestPageFlag
     * @return
     */
    public String generateRequestCode(String requestPageFlag){
        mark(requestPageFlag);
        RequestPageFlagEntity requestPageFlagEntity = requestPageFlagEntityMap.get(requestPageFlag);
        return requestPageFlagEntity.generateRequestCode();
    }

    /**
     * 根据页面请求标识获取这个页面所有自动生成的请求码
     * @param requestPageFlag
     * @return
     */
    public Set<String> getRequestCodeSet(String requestPageFlag){
        RequestPageFlagEntity requestPageFlagEntity = requestPageFlagEntityMap.get(requestPageFlag);
        if(requestPageFlagEntity != null){
            return requestPageFlagEntity.getRequestCodeSet();
        }else{
            return null;
        }
    }

    /**
     * 根据页面请求标识清空这个页面所有自动生成的请求码
     * @param requestPageFlag
     */
    public void clearRequestCodeSet(String requestPageFlag){
        RequestPageFlagEntity requestPageFlagEntity = requestPageFlagEntityMap.get(requestPageFlag);
        if(requestPageFlagEntity != null) {
             requestPageFlagEntity.clearRequestCodeSet();
        }
    }


    /**
     * 请求标识实体
     */
    class RequestPageFlagEntity {
        private String requestPageFlag;
        private Set<String> requestCodeSet;
        public RequestPageFlagEntity(String requestPageFlag) {
            this.requestPageFlag = requestPageFlag;
            this.requestCodeSet = new LinkedHashSet<>();
        }

        public String generateRequestCode(){
            String requestCode = requestPageFlag + requestCodeSet.size();
            requestCodeSet.add(requestCode);
            return requestCode;
        }

        public Set<String> getRequestCodeSet() {
            return requestCodeSet;
        }


        public void clearRequestCodeSet() {
            requestCodeSet.clear();
        }
    }
}
